/**
 * 
 */
package com.lorizz.model.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import com.lorizz.model.PersistenceRepository;

/**
 * @author wind hong
 *
 */
public abstract class AbstractRepository implements PersistenceRepository {
    
    protected EntityManager entityManager;
    
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    /* (non-Javadoc)
     * @see com.lorizz.model.PersistenceRepository#persist(java.lang.Object)
     */
    @Override
    public <T> T persist(T entity) {
        entityManager.persist(entity);
        return entity;
    }

    /* (non-Javadoc)
     * @see com.lorizz.model.PersistenceRepository#remove(java.lang.Object)
     */
    @Override
    public <T> void remove(T entity) {
        entityManager.remove(entity);
    }

    /* (non-Javadoc)
     * @see com.lorizz.model.PersistenceRepository#getCriteriaBuilder()
     */
    @Override
    public CriteriaBuilder getCriteriaBuilder() {
        return entityManager.getCriteriaBuilder();
    }

    /* (non-Javadoc)
     * @see com.lorizz.model.PersistenceRepository#executeQuery(javax.persistence.criteria.CriteriaQuery)
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> List<T> executeQuery(CriteriaQuery<?> query) {
        List<T> result = new ArrayList<T>();
        for (Object o : entityManager.createQuery(query).getResultList()) {
            result.add((T)o);
        }
        return result;
    }

    /* (non-Javadoc)
     * @see com.lorizz.model.PersistenceRepository#executeQuery(javax.persistence.criteria.CriteriaQuery, int, int)
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> List<T> executeQuery(CriteriaQuery<?> query, int first, int size) {
        TypedQuery<?> q = entityManager.createQuery(query);
        if (first > -1)
            q.setFirstResult(first);
        if (size > 0)
            q.setMaxResults(size);
        List<T> result = new ArrayList<T>();
        for (Object o : q.getResultList()) {
            result.add((T)o);
        }
        return result;
    }

}
